﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public static class LangResTool
{
    static string langResDir = "lang_res";

    static void CreateLangResource(SystemLanguage language)
    {
        EditorCommonTool.ProcessSelectionObjs("*", (path) =>
            {
                if(!System.IO.File.Exists(path))
                {
                    return;
                }
                    
                string destPath = path.Replace(ResourcesEx.BundleResDir + "/", "");
                destPath = ResourcesEx.BundleResDir + "/" + LangManager.GetResourcePath(destPath, language);

                string dirPath = System.IO.Path.GetDirectoryName(destPath);
                System.IO.Directory.CreateDirectory(dirPath);
                System.IO.File.Copy(path, destPath, true);
            });

        AssetDatabase.Refresh();
    }

    public static void CopyRes(string path, SystemLanguage language)
    {
        string destPath = path.Replace(ResourcesEx.BundleResDir + "/", "");
        destPath = ResourcesEx.BundleResDir + "/" + LangManager.GetResourcePath(destPath, language);

        string dirPath = System.IO.Path.GetDirectoryName(destPath);
        System.IO.Directory.CreateDirectory(dirPath);
        System.IO.File.Copy(path, destPath, true);
    }

	[MenuItem("Assets/Custom/LangResource/Create/ChineseSimplified")]
    public static void ChineseSimplified()
    {
        CreateLangResource(SystemLanguage.ChineseSimplified);
    }

    [MenuItem("Assets/Custom/LangResource/Create/ChineseTraditional")]
    public static void ChineseTraditional()
    {
        CreateLangResource(SystemLanguage.ChineseTraditional);
    }

	[MenuItem("Assets/Custom/LangResource/Create/Korean")]
	public static void Korean()
	{
		CreateLangResource(SystemLanguage.Korean);
	}
		
	public static Dictionary<string, HashSet<string>> GetMultiLangSpriteSet()
	{
		Dictionary<string, HashSet<string>> resultSet = new Dictionary<string, HashSet<string>>();
        string[] paths = System.IO.Directory.GetFiles(ResourcesEx.BundleResDir + "/" + LangManager.GetResDir(), "*", System.IO.SearchOption.AllDirectories);
		for (int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			if (string.IsNullOrEmpty(System.IO.Path.GetExtension(path)))
			{
				continue;
			}

			if (path.EndsWith(".meta"))
			{
				continue;
			}

			string tempPath = LangManager.GetNoLangPath(path);
            tempPath = ResourcesEx.BundleResDir + "/" + tempPath;

			HashSet<string> tempSet = null;
			if (!resultSet.TryGetValue(tempPath, out tempSet))
			{
				tempSet = new HashSet<string>();
				resultSet.Add(tempPath, tempSet);
			}

			tempSet.Add(path);
		}

		return resultSet;
	}

	[MenuItem("Custom/LangResource/AddMultiLangSpriteToPrefab")]
	public static void AddMultiLangSpriteToPrefab()
	{
		Dictionary<string, HashSet<string>> spriteSet = GetMultiLangSpriteSet();

        string[] paths = System.IO.Directory.GetFiles(ResourcesEx.BundleResDir + "/prefab/ui/", "*.prefab", System.IO.SearchOption.AllDirectories);
		for (int i = 0; i < paths.Length; i++)
		{
			string path = paths[i];
			GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(path);

            UI2DSpriteEx[] sprites = null;
            GameObject obj = null;
            bool multiComponentAdded = false;
            bool needInstance = true;
            if(needInstance)
            {
                obj = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
                sprites = obj.GetComponentsInChildren<UI2DSpriteEx>(true);
            }
            else
            {
                sprites = prefab.GetComponentsInChildren<UI2DSpriteEx>(true);
            }

            for (int j = 0; j < sprites.Length; j++)
            {
                UI2DSpriteEx sprite = sprites[j];
                string spritePath = AssetDatabase.GetAssetPath(sprite.sprite2D);
                if (spriteSet.ContainsKey(spritePath))
                {
                    MultiLangSprite multiLangSprite = sprite.gameObject.GetComponent<MultiLangSprite>();
                    if (multiLangSprite == null)
                    {
                        multiLangSprite = sprite.gameObject.AddComponent<MultiLangSprite>();
                    }
                    multiLangSprite.sprite = sprite;
                    string assetPath = System.IO.Path.ChangeExtension(spritePath.Replace(ResourcesEx.BundleResDir + "/", ""), "");
                    assetPath = assetPath.Substring(0, assetPath.Length - 1);
                    multiLangSprite.spritePath = assetPath;

                    multiComponentAdded = true;
                }
            }

            if(needInstance)
            {
                if(multiComponentAdded)
                {
                    PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.Default);
                }
                GameObject.DestroyImmediate(obj);
            }
            else
            {
//                EditorUtility.SetDirty(prefab);
                Undo.RecordObject(prefab, "add MultiLangSprite");
            }
		}
			
		AssetDatabase.Refresh();
		AssetDatabase.SaveAssets();
	}

	[MenuItem("Custom/LangResource/DeleteNoUseResources")]
	public static void DeleteNoUseResources()
	{
		Dictionary<string, HashSet<string>> spriteSet = GetMultiLangSpriteSet();

		foreach (var entry in spriteSet)
		{
			if (!System.IO.File.Exists(entry.Key))
			{
				foreach (var temp in entry.Value)
				{
					System.IO.File.Delete(temp);
				}
			}
		}
	}



//    [MenuItem("Custom/OldProject/Prefab/ReferenceToIcpResource")]
//    public static void ReferenceToIcpResource()
//    {
//        return;
//
//        if(SwitchConfig.icp != 1)
//        {
//            return;
//        }
//
//        string[] exts = new string[]{".meta"};
//        string[] resPaths = CreateSpriteSheet.bundleDir;
//        for(int j = 0; j < resPaths.Length; j++)
//        {
//            string resPath = resPaths[j];
//            string icpResPath = resPath + "/" + ResourcesEx.IcpResDirName;
//
//            for(int i = 0; i < exts.Length; i++)
//            {
//                string[] paths = Directory.GetFiles(icpResPath, "*" + exts[i], SearchOption.TopDirectoryOnly);
//                for(int k = 0; k < paths.Length; k++)
//                {
//                    string path = paths[k];
//                    string srcPath = path.Replace(ResourcesEx.IcpResDirName + "/", "");
//                    srcPath = srcPath.Replace(ResourcesEx.dirSymbol, '/');
//
//                    if(SwitchConfig.icp == 1)
//                    {
//                        if(File.Exists(srcPath))
//                        {
//                            string tempPath = path + ".temp";
//                            CommonUtil.Move(path, tempPath);
//                            CommonUtil.Move(srcPath, path);
//                            CommonUtil.Move(tempPath, srcPath);
//                        }
//                    }
//                    else
//                    {
//                        if(File.Exists(srcPath))
//                        {
//                            CommonUtil.Delete(path.Replace(".meta", ""));
//                            CommonUtil.Delete(path);
//                        }
//                    }
//                }
//            }
//        }
//
//        AssetDatabase.Refresh();
//    }
}
